package Server;

import ClientFront.Net.MsgTypeEnum;
import ClientFront.NetMsg;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class DealUserMsg implements Runnable{
    boolean isRunning = true;
    Socket mySocket;
    BlankTypeEnum myType;
    Server theServer;
    DealUserMsg(Socket socket,BlankTypeEnum userChessType){
        mySocket = socket;
        myType = userChessType;
    }

    public DealUserMsg setTheServer(Server theServer) {
        this.theServer = theServer;
        return this;
    }

    public void setRunning(boolean running) {
        isRunning = running;
    }

    @Override
    public void run() {
        try {
            ObjectOutputStream output = mySocket == theServer.Player1?theServer.output1:theServer.output2;
            ObjectInputStream input = mySocket == theServer.Player1?theServer.input1:theServer.input2;
            while(isRunning)
            {
                Thread.sleep(ServerConsts.SLEEP_MILLIS);
                int turn = theServer.getTurnNum();
                if(Server.nextTrun && turn%2 == 1){
                    System.out.println("turn="+turn);
                    Server.nextTrun = false;
                    theServer.sendToPlayer1(new NetMsg(MsgTypeEnum.YOURTURN));
                }else if(theServer.nextTrun&& turn%2 == 0){
                    System.out.println("turn="+turn);
                    theServer.nextTrun = false;
                    theServer.sendToPlayer2(new NetMsg(MsgTypeEnum.YOURTURN));
                }
                NetMsg newMsg = (NetMsg) input.readObject();
                dealMsg(newMsg);
            }
        }catch (Exception e){}
    }

    void dealMsg(NetMsg msg){
        System.out.println("DEALMSG收到消息："+msg.getMsgType().name());
        switch (msg.getMsgType()){
            case MSG:case ACT:
                theServer.sendToOther(msg,mySocket);
                break;

            case QUIT:case ACTACK: case ACTDENY:
            case STEP:
                theServer.dealMsg(msg,mySocket);
                if(msg.getMsgType() == MsgTypeEnum.STEP &&theServer.nextTrun == false){
                    theServer.nextTrun = true;
                }
                break;
        }
    }
}
